package com.nononsenseapps.feeder.ui.rule

import android.app.Application
import androidx.lifecycle.viewModelScope
import androidx.paging.LivePagedListBuilder
import com.nononsenseapps.feeder.db.DEFAULT_PAGE_SIZE
import com.nononsenseapps.feeder.db.room.AppDatabase
import com.nononsenseapps.feeder.db.entity.FeedRule
import com.nononsenseapps.feeder.db.room.FeedRuleDao
import com.nononsenseapps.feeder.db.room.ID_ALL_FEEDS
import com.nononsenseapps.feeder.ui.base.CoroutineScopedViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


class FeedRuleViewModel (application: Application): CoroutineScopedViewModel(application){

    val feedRuleDao: FeedRuleDao = AppDatabase.getInstance(application).feedRuleDao()

    fun livePagedAll(feedId:Long) = LivePagedListBuilder( if( feedId == ID_ALL_FEEDS) feedRuleDao.listAll() else feedRuleDao.listAllWithFeed(feedId), DEFAULT_PAGE_SIZE).build()

    fun updateFeedAble(id: Long, able: Boolean) =viewModelScope.launch(Dispatchers.IO){
        feedRuleDao.updateFeedAble(id,able)
    }

    fun deleteFeedRule(id: Long) =viewModelScope.launch(Dispatchers.IO){
        feedRuleDao.delete(FeedRule(id))
    }

}